export default {
    text() {
        console.log("测试，测试！！！")
    },
    // 下载TXT
    downloadTXT(filename, text) {
        var element = document.createElement('a');
        element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
        element.setAttribute('download', filename);
        element.style.display = 'none';
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
    },
    // 提取纯文本
    ToText(HTML) {
        var input = HTML;
        if (input) {
            return input.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi, '').replace(/<[^>]+?>/g, '').replace(/\s+/g, ' ').replace(/ /g, ' ').replace(/>/g, ' ').replace(/&nbsp;/ig, ' ');
        } else {
            return input;
        }
    },
    /**
     * 函数防抖
     */
    debounce(fn, wait = 1000) {
        let timer;
        return function () {
            let context = this;
            let args = arguments;
            if (timer) clearTimeout(timer);
            timer = setTimeout(() => {
                fn.apply(context, args);
            }, wait)
        }
    },
    /**
     * 函数节流
     */
    throttle(fn, wait = 1000) {
        let timer;
        return function () {
            if (timer != null) return;
            let context = this;
            let args = arguments;
            fn.apply(context, args);
            timer = setTimeout(() => {
                timer = null;
            }, wait);
        }
    },

    // 检测是否有中文
    ifYouNeed(str, type) {
        if (type == 'Chinese') {
            if (escape(str).indexOf("%u") < 0) {
                return false
            } else {
                return true
            }
        }
    },

    // 计算相差天数
    datedifference(sDate1, sDate2) {    //sDate1和sDate2是2006-12-18格式 
        var dateSpan,
            iDays;
        sDate1 = Date.parse(sDate1);
        sDate2 = Date.parse(sDate2);
        dateSpan = sDate2 - sDate1;
        dateSpan = Math.abs(dateSpan);
        console.log(dateSpan)
        iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
        return iDays
    },


    // 时间转时间戳
    timeStamp(date) {
        date = date.substring(0, 19);
        date = date.replace(/-/g, '/');
        var timestamp = new Date(date).getTime();
        return timestamp
    },
    //计算字符总长度
    bytesLnegth(str) {
        var count = str.length;
        for (var i = 0; i < str.length; i++) {
            if (str.charCodeAt(i) > 255) {
                count++;
            }
        }
        return count;
    },
    //字符串转化为json函数代码:
    formatasjson(str) {
        try {
            var json = $.parseJSON(str);
        } catch (e) {
            $(".spin-container").hide();
            // alertModal("提示","网络不稳定，请您稍后重试！");
            return false;
        }
        if ("message" in json) {
            json.message = getTipLanguage(json.message);
        }
        return json;
    },
    //json转化为字符串函数代码:
    forstring(json) {
        return JSON.stringify(json);
    },
    //设置cookie
    setCookie(name, value) {
        var exp = new Date();
        exp.setTime(exp.getTime() + 30 * 24 * 60 * 60 * 1000);
        document.cookie = name + "=" + encodeURI(value) + ";expires=" + exp.toGMTString();
    },
    //获取cookie
    getCookie(c_name) {
        if (document.cookie.length > 0) {
            var c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                var c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) c_end = document.cookie.length;
                return decodeURI(document.cookie.substring(c_start, c_end));
                //编码，解码 encodeURI()   decodeURI()
            }
        }
        return "";
    },
    //删除cookie
    delCookie(name) {
        const that = this
        var exp = new Date();
        exp.setTime(exp.getTime() - 3600);
        var cval = that.getCookie(name);
        if (cval != null) {
            document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString() + "";
            document.cookie = "SAAS4=0;expires=" + exp.toGMTString() + ";path=/module";
            document.cookie = "SAAS4=0;expires=" + exp.toGMTString() + ";path=/testor";
            document.cookie = "SAAS4=0;expires=" + exp.toGMTString() + ";path=/client";
            document.cookie = "SAAS4=0;expires=" + exp.toGMTString() + ";path=/client2";
        }
    },
    //文件base64编码并且保存sessionStorage->"file_base64"
    base64(id) {
        var file = $("#" + id);
        var file_data = file[0].files[0];
        var reader = new FileReader();
        reader.readAsDataURL(file_data);
        reader.onload = function (e) {
            var file_str = e.target.result;
            sessionStorage.setItem("file_base64", file_str);
        };
    },


    //获取时间函数
    getNowTime() {
        var now = new Date();
        var time = now.getFullYear() + "-" + ((now.getMonth() + 1) < 10 ? "0" : "") + (now.getMonth() + 1) + "-" + (now.getDate() < 10 ? "0" : "") + now.getDate() + "" +
            " " + (now.getHours() < 10 ? "0" + now.getHours() : now.getHours()) + ":" + (now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes()) + ":"
            + (now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds());
        return time;
    },
    getTime(type, num) {
        var date = new Date();
        var time = "";
        switch (type) {
            case "month":
                var ms = num * (1000 * 60 * 60 * 24 * 30);
                var now = new Date(date.getTime() + ms);
                time = now.getFullYear() + "-" + ((now.getMonth() + 1) < 10 ? "0" : "") + (now.getMonth() + 1);
                return time;
                break;
            case "day":
                var ms = num * (1000 * 60 * 60 * 24);
                var now = new Date(date.getTime() + ms);
                time = now.getFullYear() + "-" + ((now.getMonth() + 1) < 10 ? "0" : "") + (now.getMonth() + 1) + "-" + ((now.getDate() < 10) ? "0" : "") + (now.getDate());
                return time;
                break;
            case "minute":
                var ms = num * (1000 * 60);
                var now = new Date(date.getTime() + ms);
                var time = now.getFullYear() + "-" + ((now.getMonth() + 1) < 10 ? "0" : "") + (now.getMonth() + 1) + "-" + (now.getDate() < 10 ? "0" : "") + now.getDate() + "" +
                    " " + (now.getHours() < 10 ? "0" + now.getHours() : now.getHours()) + ":" + (now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes());
                return time;
                break;
            default:
                return "";
                break;
        }
    },
    format(sjc, type) {
        const that = this
        var time = new Date(sjc);
        var y = time.getFullYear();
        var m = time.getMonth() + 1;
        var d = time.getDate();
        var h = time.getHours();
        var mm = time.getMinutes();
        var s = time.getSeconds();
        if (type == "day") {
            return y + '-' + that.add0(m) + '-' + that.add0(d);
        } else {
            return y + '-' + that.add0(m) + '-' + that.add0(d) + ' ' + that.add0(h) + ':' + that.add0(mm) + ':' + that.add0(s);
        }
    },
    add0(m) { return m < 10 ? '0' + m : m },
    //获取随机数 x - y
    getRandom(x, y) {
        var rand = parseInt(Math.random() * (x - y + 1) + y);
        return rand;
    },
    //生成随机数【1，9】
    randomNum(minNum, maxNum) {
        switch (arguments.length) {
            case 1:
                return parseInt(Math.random() * minNum + 1);
                break;
            case 2:
                return parseInt(Math.random() * (maxNum - minNum + 1) + minNum);
                break;
            default:
                return 0;
                break;
        }
    },
    //获取iframe参数 id为iframe（id）
    GetIframeQueryString(name, id) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.parent.document.getElementById(id).contentWindow.location.search.substr(1).match(reg);
        if (r != null) {
            return decodeURI(r[2]);
        }
        return null;
    },

    // import {websiteName} from "../../config/webConfig"
    getTipLanguage(key) {
        var language = LANGS.accountState;
        var str = key;
        if (key in language) {
            str = language[key];
        }
        return str;
    },
    //截取字符串长度 英文1 汉字2
    subString(str, len, hasDot) {
        var newLength = 0;
        var newStr = "";
        var chineseRegex = /[^\x00-\xff]/g;
        var singleChar = "";
        var strLength = str.replace(chineseRegex, "**").length;
        for (var i = 0; i < strLength; i++) {
            singleChar = str.charAt(i).toString();
            if (singleChar.match(chineseRegex) != null) {
                newLength += 2;
            }
            else {
                newLength++;
            }
            if (newLength > len) {
                break;
            }
            newStr += singleChar;
        }
        if (hasDot && strLength > len) {
            newStr += "...";
        }
        return newStr;
    },
    /**
     *  redis 存储
     *  action 操作方法 get set del clear
     *  store_key  => custom_search 保存的对应 key
     *  search  搜索值
     */
    redisWork(action, search, store_key) {
        search = decodeURI(search);
        var data = {
            module: "search_key",
            action: action,
            search: search,
            store_key: store_key
        };
        $.post(requestRedis(), data, function (res) {
            showRedisData(res);
        })
    },
    //冒泡事件
    stopPropagation(e) {
        if (e.stopPropagation) {
            e.stopPropagation();
        } else {
            e.cancelBubble = true;
        }
    },
    /**
     * data是json对象，Name是根据什么字段去重
     */
    jsonDelDouble(data, Name) {
        var map = {}, dest = [];
        for (var i = 0; i < data.length; i++) {
            var ai = data[i];
            if (i == 0) {
                dest.push(ai);
            } else {
                var filterData = dest.filter(function (e) {
                    return e[Name] == ai[Name];
                })
                if (filterData.length == 0) {
                    dest.push(ai);
                }
            }
        }
        return dest;
    },

    //width、height调用时传入具体像素值，控制大小 ,不传则默认图像大小
    getBase64Image(img, width, height) {
        var canvas = document.createElement("canvas");
        canvas.width = width ? width : img.width;
        canvas.height = height ? height : img.height;

        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        var dataURL = canvas.toDataURL();
        return dataURL;
    },
    getCanvasBase64(img) {
        const that = this;
        var image = new Image();
        //至关重要
        image.crossOrigin = '';
        image.src = img;
        //至关重要
        var deferred = $.Deferred();
        if (img) {
            image.onload = function () {
                console.log(that.getBase64Image);
                deferred.resolve(that.getBase64Image(image));//将base64传给done上传处理
                // document.getElementById("container2").appendChild(image);
            }
            return deferred.promise();//问题要让onload完成后再return sessionStorage['imgTest']
        }
    },
    // 滚动到顶部
    scrollTop(element, scrollTop) {
        $(element).animate({
            scrollTop
        }, 500);
    }
}